package com.platform.core.service.impl;

import com.querydsl.core.BooleanBuilder;
import com.platform.comm.common.service.CommQueryExportService;
import com.platform.comm.entity.CommBatchInfoEntity;
import com.platform.comm.entity.QCommBatchInfoEntity;
import com.platform.comm.jwt.JwtTokenUtil;
import com.platform.comm.jwt.TokenInfoUtil;
import com.platform.comm.service.ICommBatchInfoBiz;
import com.platform.comm.util.DateTimeUtil;
import com.platform.comm.web.results.PageListJsonResult;
import com.platform.core.service.SysUserService;
import com.platform.vo.ExportRecordsDto;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.querydsl.QSort;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.util.MultiValueMap;

import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * 查询导入结果service
 *
 * @author lch 2020/01/09
 */
@Service
@Slf4j
public class CommQueryExportServiceImpl implements CommQueryExportService {
    private static final QCommBatchInfoEntity qDirBatchInfoEntity = QCommBatchInfoEntity.dirBatchInfoEntity;

    private final ICommBatchInfoBiz dirBatchInfoBiz;
    private final SysUserService sysUserService;
    private final TokenInfoUtil tokenInfoUtil;

    public CommQueryExportServiceImpl(ICommBatchInfoBiz dirBatchInfoBiz, SysUserService sysUserService, TokenInfoUtil tokenInfoUtil) {
        this.dirBatchInfoBiz = dirBatchInfoBiz;
        this.sysUserService = sysUserService;
        this.tokenInfoUtil = tokenInfoUtil;
    }

    @Override
    public PageListJsonResult<ExportRecordsDto> queryExportRecords(Pageable pageable, MultiValueMap<String, String> parameters) {
        Assert.notEmpty(parameters.get("jobType"), "任务类型不能为空！");
        JwtTokenUtil.JwtUser jwtUser = tokenInfoUtil.getUser();
        if (pageable.getSort().isUnsorted()) {
            pageable = PageRequest.of(pageable.getPageNumber(), pageable.getPageSize(), QSort.by(qDirBatchInfoEntity.createDate.desc(), qDirBatchInfoEntity.id.desc()));
        }
        BooleanBuilder bool = builderConditions(parameters);
        if (!jwtUser.isAdmin()) {
            bool.and(qDirBatchInfoEntity.createBy.eq(jwtUser.getId()));
        }
        Page<CommBatchInfoEntity> entities = dirBatchInfoBiz.queryByPage(bool, pageable);
        return new PageListJsonResult<>(entities.map(entity -> {
            ExportRecordsDto exportRecordsDto = entity.toDto();
            this.sysUserService.queryById(entity.getCreateBy()).ifPresent(user -> exportRecordsDto.setCreateUserName(user.getRealName()));
            return exportRecordsDto;
        }));
    }

    @Override
    public ImmutablePair<Path, String> getCommFile(String batchInfoId) {
        CommBatchInfoEntity dirBatchInfoEntity = dirBatchInfoBiz.fetchById(batchInfoId);
        Path path = Paths.get(dirBatchInfoEntity.getJobResult());
        return ImmutablePair.of(path, dirBatchInfoEntity.getJobName() + ".xlsx");
    }

    private BooleanBuilder builderConditions(MultiValueMap<String, String> parameters) {
        String jobType = parameters.getFirst("jobType");
        String beginTime = parameters.getFirst("beginTime");
        String endTime = parameters.getFirst("endTime");
        String status = parameters.getFirst("status");
        BooleanBuilder builder = new BooleanBuilder();
        if (StringUtils.isNotEmpty(jobType)) {
            builder.and(qDirBatchInfoEntity.jobType.eq(jobType));
        }
        if (StringUtils.isNotEmpty(beginTime) && StringUtils.isNotEmpty(endTime)) {
            String plusEndTime = DateTimeUtil.toStdDateStr(DateTimeUtil.toLocalDate(endTime).plusDays(1));
            builder.and(qDirBatchInfoEntity.createDate.between(beginTime, plusEndTime));
        }
        if (StringUtils.isNotEmpty(status)) {
            builder.and(qDirBatchInfoEntity.jobStatus.eq(status));
        }
        return builder;
    }
}
